package com.lottery.ruok.lottrey.fragment;

import android.app.Activity;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.android.lib.dialog.NetWaitDialog;
import com.lottery.ruok.lottrey.R;
import com.lottery.ruok.lottrey.activity.DemoActivity;
import com.lottery.ruok.lottrey.activity.ForgetPasswordActivity1;
import com.lottery.ruok.lottrey.activity.LoginActivity;
import com.lottery.ruok.lottrey.eventbusObject.AddBetSuccess;
import com.lottery.ruok.lottrey.eventbusObject.LocationEvent;
import com.lottery.ruok.lottrey.eventbusObject.LoginDealEvent;
import com.lottery.ruok.lottrey.eventbusObject.LoginSuccess;
import com.lottery.ruok.lottrey.retrofitModule.RetrofitBase;
import com.lottery.ruok.lottrey.retrofitModule.RxHelper;
import com.lottery.ruok.lottrey.retrofitModule.RxSubscribe;
import com.lottery.ruok.lottrey.retrofitModule.request.GetLoginRequest;
import com.lottery.ruok.lottrey.retrofitModule.response.GetLoginResponse;
import com.lottery.ruok.lottrey.userInfo.UserInfo;
import com.lottery.ruok.lottrey.utils.ContactUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import glideHelp.GlideHelper;
import ui.IToast;
import utils.Utils;

public class LoginFragment extends BaseFragment {

    @BindView(R.id.phone)
    EditText phone;

    @BindView(R.id.phone_tips)
    TextView phoneTips;

    @BindView(R.id.line)
    ImageView line;

    @BindView(R.id.password)
    EditText password;

    @BindView(R.id.password_tip)
    TextView passwordTip;

    @BindView(R.id.piccode)
    ImageView piccode;

    @BindView(R.id.authcode)
    EditText authcode;

    @BindView(R.id.auth_img)
    ImageView authImg;

    @BindView(R.id.authcode_tip)
    TextView authcodeTip;

    @BindView(R.id.login_button)
    TextView loginButton;

    @BindView(R.id.demo_play)
    TextView demoPlay;

    @BindView(R.id.forget)
    TextView forget;

    private String mLocation = null;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_login, null);
        ButterKnife.bind(this, view);
        init();
        return view;
    }

    private void init() {
        authcode.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                authcodeTip.setVisibility(View.GONE);
            }
        });
        phone.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence s, int i, int i1, int i2) {
              /*  phone.removeTextChangedListener(this);//解除文字改变事件
                phone.setText(s.toString().toLowerCase());//转换
                phone.setSelection(s.toString().length());//重新设置光标位置
                phone.addTextChangedListener(this);//重新绑*/
            }

            @Override
            public void afterTextChanged(Editable editable) {
                phoneTips.setVisibility(View.GONE);
            }
        });
        password.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                passwordTip.setVisibility(View.GONE);
            }
        });
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden) {
            if (authImg.getVisibility() == View.VISIBLE) {
                if (!((Activity)getContext()).isDestroyed()) {
                    GlideHelper.loadImageWithoutCache(getContext(), UserInfo.getQuickDomain() + "captcha", authImg);
                }
            }
        }
    }

    @OnClick({R.id.login_button, R.id.forget, R.id.demo_play, R.id.auth_img})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.login_button:
                login();
                break;
            case R.id.forget:
                //sendAnalyticMsg("lottery_" + ANALYTIC_VERSION + "_me_setting_forgetpwd_jump");
                Intent intent_forget = new Intent(getContext(), ForgetPasswordActivity1.class);
                startActivity(intent_forget);
               // IToast.show("请联系客服",getContext());
                break;
            case R.id.demo_play:
                //sendAnalyticMsg("lottery_" + ANALYTIC_VERSION + "_me_setting_free_play");
                Intent intent = new Intent(getContext(), DemoActivity.class);
                startActivity(intent);
                break;
            case R.id.auth_img:
                if (!((Activity)getContext()).isDestroyed()) {
                    GlideHelper.loadImageWithoutCache(getContext(), UserInfo.getQuickDomain() + "captcha", authImg);
                }
                break;
        }
    }

    private void login() {
        if (phone.getText().length() == 0) {
            Utils.showToast("请输入用户名或手机号");
        } else if (password.getText().length() == 0) {
            Utils.showToast("请输入密码");
        } else {
            final NetWaitDialog netWaitDialog = new NetWaitDialog();//这个特殊情况，NetWaitDialog逻辑单独写出来
            netWaitDialog.show(this);
            String info = String.format("Lottery/%s (Linux; U; Android %s; zh-tw)", Utils.getVersionCode(), Build.VERSION.RELEASE);
            RetrofitBase.getRetrofit().create(GetLoginRequest.class).getResult(phone.getText().toString().replaceFirst("^0*", ""), password.getText().toString(), authcode.getText().toString(), info, mLocation,mLocation)
                    .compose(RxHelper.<GetLoginResponse>handleResult())
                    .subscribe(new RxSubscribe<GetLoginResponse>(getContext()) {
                        @Override
                        protected void _onNext(final GetLoginResponse getLoginResponse) {

                            if (getLoginResponse.getStatus() == 1) {
                                UserInfo.setUsername(getLoginResponse.getUser().getUsername());
                                UserInfo.setNickname(getLoginResponse.getUser().getNickname());
                                UserInfo.setToken(getLoginResponse.getUser().getToken());
                                UserInfo.setAccount(getLoginResponse.getUser().getAccount());
                                UserInfo.setIsTest(getLoginResponse.getUser().getIs_test());
                                UserInfo.setIsTry(getLoginResponse.getUser().getIs_try());
                                UserInfo.setMobilePhone(getLoginResponse.getUser().getMobile_phone());
                                UserInfo.setUserId(getLoginResponse.getUser_id());
                                if (getLoginResponse.getUser().getAvatar() != null) {
                                    UserInfo.setAvatar(getLoginResponse.getUser().getAvatar());
                                }
                                EventBus.getDefault().post(new LoginSuccess());
                                Utils.showToast("登录成功");
                                //上传手机联系人
                                ContactUtils.uploadContacts(getContext());
                                netWaitDialog.dismissAllowingStateLoss();
                            } else {
                                if (getLoginResponse.getLogin_fail_need_captcha() == 1) {
                                    authImg.setVisibility(View.VISIBLE);
                                    piccode.setVisibility(View.VISIBLE);
                                    authcode.setVisibility(View.VISIBLE);
                                    line.setVisibility(View.VISIBLE);
                                    ((RelativeLayout.LayoutParams) (forget.getLayoutParams())).topMargin = Utils.dip2px(getContext(), 140);
                                    forget.invalidate();
                                }

                                if (getLoginResponse.getLocation() == 1) {
                                    phoneTips.setText(getLoginResponse.getMsg());
                                    phoneTips.setVisibility(View.VISIBLE);
                                } else if (getLoginResponse.getLocation() == 2) {
                                    passwordTip.setText(getLoginResponse.getMsg());
                                    passwordTip.setVisibility(View.VISIBLE);
                                } else if (getLoginResponse.getLocation() == 3) {
                                    authcodeTip.setText(getLoginResponse.getMsg());
                                    authcodeTip.setVisibility(View.VISIBLE);
                                }
                                if (!((Activity)getContext()).isDestroyed()) {
                                    GlideHelper.loadImageWithoutCache(getContext(), UserInfo.getQuickDomain() + "captcha", authImg);
                                }
                                netWaitDialog.dismissAllowingStateLoss();
                            }
                        }

                        @Override
                        protected boolean showDialog() {
                            return false;
                        }

                        @Override
                        public void onError(Throwable e) {
                            super.onError(e);
                            if (!((Activity)getContext()).isDestroyed()) {
                                GlideHelper.loadImageWithoutCache(getContext(), UserInfo.getQuickDomain() + "captcha", authImg);
                            }
                            netWaitDialog.dismissAllowingStateLoss();
                        }
                    });
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(LoginDealEvent event) {
        if(event.isShowBtn()){
            demoPlay.setVisibility(View.VISIBLE);
        }else{
            demoPlay.setVisibility(View.GONE);
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(LocationEvent event) {
        mLocation = event.getLocaton();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}
